import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';

interface AnimatedTransitionProps {
    inAnimation?: string; //进入动画类名
    outAnimation?: string; //退出动画类名
    duration?: number; //动画持续时间（ms）
    // onExited?: () => void; //退出动画结束后的回调
    children: React.ReactNode | ((triggerExit: () => void) => React.ReactNode);
    // 可选：跳转目标路由
    to?: string;
    // 可选：是否启用自动跳转
    autoExit?: boolean;
}

const AnimatedTransition: React.FC<AnimatedTransitionProps> = ({
    inAnimation = 'animate__fadeIn',
    outAnimation = 'animate__fadeOut',
    duration = 1000,
    // onExited,
    children,
    to,
    autoExit = false,
}) => {
    const [acimateClass, setAnimateClass] = useState(inAnimation);
    const navigate = useNavigate();
    const location = useLocation();

    // 入场动画
    useEffect(() => {
        setAnimateClass(inAnimation);
    }, [location.pathname, inAnimation]);

    // 自动出场动画并跳转
    useEffect(() => {
        if (autoExit && to) {
            const timer = setTimeout(() => {
                setAnimateClass(outAnimation);
                setTimeout(() => {
                    navigate(to, { replace: true });
                }, duration);
            }, 1500); // 1.5秒后自动跳转
            return () => clearTimeout(timer);
        }
    }, [autoExit, to, outAnimation, duration, navigate]);

    return (
        <div
            className={`animate__animated ${acimateClass}`}
            style={{ animationDuration: `${duration}ms` }}
        >
            {typeof children === 'function' ? null : children}
        </div>
    )
}

export default AnimatedTransition;